package com.sskj.lib.mvchelper;

import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.MutableLiveData;

import com.shizhefei.mvc.IAsyncDataSource;
import com.shizhefei.mvc.RequestHandle;
import com.shizhefei.mvc.ResponseSender;

import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 :吕志豪
 * 简书：https://www.jianshu.com/u/6e525b929aac
 * github：https://github.com/lvzhihao100
 * 描述：
 * 创建时间：2018-07-27 08:27
 * 下拉刷新，展示各种状态界面，请求数据
 */
public class RefreshDataSource<T> implements IAsyncDataSource<List<T>> {
    private MutableLiveData tMutableLiveData;
    private ResponseSender sender;
    private OnLoadSource onLoadSource;
    private Disposable subscribe;

    public interface OnLoadSource<T> {
        Flowable<List<T>> loadData();
    }

    public RefreshDataSource(LifecycleOwner lifecycleOwner, OnLoadSource onLoadSource) {
        this.onLoadSource = onLoadSource;
        tMutableLiveData = new MutableLiveData<>();
        tMutableLiveData.observe(lifecycleOwner, t -> {
            if (sender != null) {
                sender.sendData(t);
            }
        });
    }

    @Override
    public RequestHandle refresh(ResponseSender<List<T>> sender) throws Exception {
        this.sender = sender;
        subscribe = onLoadSource.loadData().subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(data -> tMutableLiveData.postValue(data), throwable -> sender.sendError(new Exception((Throwable) throwable)));
        return new RequestHandle() {
            @Override
            public void cancle() {
                if (!subscribe.isDisposed()) {
                    subscribe.dispose();
                }
            }

            @Override
            public boolean isRunning() {
                return !subscribe.isDisposed();
            }
        };
    }

    @Override
    public RequestHandle loadMore(ResponseSender<List<T>> sender) throws Exception {
        return null;
    }

    @Override
    public boolean hasMore() {
        return false;
    }

}
